package com.zhp.farmerclient.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zhp.farmerclient.common.Result;
import com.zhp.farmerclient.entity.User;
import com.zhp.farmerclient.service.UserService;
import com.zhp.farmerclient.utils.JwtUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/user")
@CrossOrigin//解决前端后端跨域问题
public class UserController {

    @Autowired
    public UserService userService;
    @Autowired
    public JwtUtils jwtUtils;

    //注册
    @PostMapping("/register")
    public Result register(@RequestBody  User user) {
        return userService.register(user);
    }
    //登录
    @GetMapping("/login")
    public Result login(@Validated @RequestParam String username, @RequestParam String password, HttpServletResponse response) {
        return userService.login(username,password,response);
    }
    // 退出
    @GetMapping("/logout")
    @RequiresAuthentication
    public Result logout() {
        SecurityUtils.getSubject().logout();
        return Result.succ();
    }
    //查询
    @GetMapping
    public List<User> findAll() {
        return userService.findAll();
    }
    //根据id查看个人信息
    @GetMapping("/check/{id}")
    public Result check(@PathVariable("id") int id){
        return userService.check(id);
    }
    //修改个人信息
    @PostMapping("/update")
    public Result update(@Validated  @RequestBody  User user){
        return userService.update(user);
    }

    //新增或修改
    @PostMapping("/insert")
    public Result save(@Validated  @RequestBody  User user){
        return userService.save(user);

    }
    //删除
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        return userService.delete(id);
    }
    //批量删除
    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) { // [1,2,3]
        return userService.deletes(ids);
    }
    // 分页查询
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                                @RequestParam Integer pageSize,
                                @RequestParam(defaultValue = "") String username,
                                @RequestParam(defaultValue = "") String email,
                                @RequestParam(defaultValue = "") String address) {

        return userService.page(pageNum,pageSize,username,email,address);
    }

    //导出
    @GetMapping("/export")
    public void export(HttpServletResponse response, @RequestParam("ids") List<Integer> ids) throws Exception {
        // 从数据库查询出所有的数据
//        List<User> list = userService.findAll();
        List<User> list = userService.export(ids);

        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("username", "用户名");
        writer.addHeaderAlias("password", "密码");
        writer.addHeaderAlias("sex", "性别");
        writer.addHeaderAlias("email", "邮箱");
        writer.addHeaderAlias("phone", "电话");
        writer.addHeaderAlias("address", "地址");
        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }
    //导入
    @PostMapping("/import")
    public Boolean imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);

        // 方式：忽略表头的中文，直接读取表的内容
        List<List<Object>> list = reader.read(1);
        List<User> users = CollUtil.newArrayList();
        for (List<Object> row : list) {
            User user = new User();
            user.setUsername(row.get(0).toString());
            user.setPassword(row.get(1).toString());
            user.setSex(row.get(2).toString());
            user.setEmail(row.get(3).toString());
            user.setPhone(row.get(4).toString());
            user.setAddress(row.get(5).toString());
            users.add(user);
        }

        userService.saveBatch(users);
        return true;
    }
}
